import React, { useState, useEffect } from 'react';
import { Input, Form, Empty, Checkbox, message, Radio } from 'antd';
import CommonModal from '@/components/CommonModal';
import { find, cloneDeep, pull } from 'lodash';
import { getGrantTreeData, getGrantTreeDetail, updateRole, addRole } from '../service';
import styles from './index.module.less';

const { TextArea } = Input;
const layout1 = { //查询表单排布
  labelCol: {
    span: 4,
  },
  wrapperCol: {
    span: 20,
  }
};

export default ({ item={}, handleOk, handleCancel }) => {

  const [form] = Form.useForm();
  const [ data, setData ] = useState([]);
  const { id, roleName, note, roleType } = item;
  const [ selectData, setSelectData ] = useState([]);
  const [ oneMenu, setOneMenu ] = useState(undefined);
  const [ twoMenu, setTwoMenu ] = useState(undefined);
  const [ menuType, setMenuType ] = useState('web');
  const [isOk, setIsOk] = useState(false);

  const [open, setOpen] = useState(false);

  useEffect(() => {
      setOpen(true);
      getAllTreeData();
      if(item.id) {
        getRoleData();
      }
  }, [])

  //请求完整的权限列表
  const getAllTreeData = async () => {
    START_LOADING();
    const res = await getGrantTreeData();
    END_LOADING();
    if(res.success) {
      setData(res.data);
    }
  }

  //请求当前角色的权限列表
  const getRoleData = async () => {
    const res = await getGrantTreeDetail({
      roleIds: id
    });
    if(res.success) {
      const data = res.data.menu;
      setSelectData(data);
    }
  }

  const onOk = () => {
    form.validateFields().then(val => {
      handleSubmit(val);
    })
  }

  const handleSubmit = async (val) => {
    const arr = cloneDeep(selectData);
    // const obj = find(data.menu, ['title', '首页']);
    // if(obj) {
    //   const menuId = obj.children[0].id;
    //   if(!arr.includes(menuId)) {
    //     arr.push(menuId);
    //   }
    // }
    let res;
    START_LOADING();
    if(id) { 
      //更新编辑
      res = await updateRole({
        ...val,
        id: id,
        menuIds: arr
      })
    } else {
      res = await addRole({
        ...val,
        id: id,
        menuIds: arr,
      })
    }
    let timer = setTimeout(() => {
      END_LOADING();
      clearTimeout(timer);
      timer = null;
    }, 300)
    if(res.success) {
      message.success('设置成功！');
      setIsOk(true);
      setOpen(false);
    }
  }

  //当前菜单是否选中
  const getChecked = id => {
    if(selectData.includes(id)) {
      return true;
    } else {
      return false;
    }
  }

  //渲染一级子菜单
  const renderOneMenu = () => {
    const renderData = getMenuData();
    if(oneMenu && renderData.length > 0) {
      const obj = find(renderData, ['id', oneMenu ]);
      if(!obj) { return null };
      if(obj.hasChildren) {
        const arr = obj.children;
        return (
          <>
            <span style={{ margin: '24px 16px 0'}} className={ styles.fontTitle }>一级子菜单:</span>
            <div style={{ lineHeight: '32px', padding: '16px', display: 'flex', flexWrap: 'wrap' }}>
              {
                  arr.map(v => {
                    if(menuType == 'app') {
                      return (
                        <Checkbox key={v.id} style={{ marginLeft: '0px' }}  className={ styles.normalChild } onChange={(e) => handleSelectTwoMenu(e, v.id)} checked={getChecked(v.id)}><span>{v.title}</span></Checkbox>
                      )
                    }
                    if(v.hasChildren) {
                      return (
                        <span onClick={() => handleClickTwoMenu(v.id)}  key={v.id} className={ v.id == twoMenu ? styles.selectChild : styles.normalChild }>{v.title}</span>
                      )
                    } else {
                      return (
                        <Checkbox style={{ marginLeft: '0px' }}  className={ styles.normalChild } onChange={(e) => handleSelectMenu(e, v.id, true)} key={v.id} checked={getChecked(v.id)}><span>{v.title}</span></Checkbox>
                      )
                    }
                  })
              }
            </div>
          </>
        )
      } else {
        return (
          <Empty description='当前菜单下无子菜单' />
        )
      }
    } else {
      return <Empty description='请先选择主菜单' />;
    }
  }

  //渲染二级子菜单
  const renderTwoMenu = () => {
    const renderData = getMenuData();
    if(oneMenu && twoMenu && renderData.length > 0) {
      const arr = find(renderData, ['id', oneMenu ]).children;
      const obj = find(arr, [ 'id', twoMenu ]);
      if(!obj) { return null };
      if(obj.hasChildren) {
        const arr = obj.children;
        return (
          <>
            <span style={{ margin: '24px 16px 0'}} className={ styles.fontTitle }>二级子菜单:</span>
            <div style={{ lineHeight: '32px', padding: '8px 16px', display: 'flex', flexWrap: 'wrap' }}>
              {
                arr.map(v => {
                  return (
                    <Checkbox style={{ marginLeft: '0px' }}  className={ styles.normalChild } onChange={(e) => handleSelectMenu(e, v.id)} checked={getChecked(v.id)} key={v.id}><span>{v.title}</span></Checkbox>
                  )
                })
              }
            </div>
          </>
        )
      }
    }
  }

  //选择菜单
  const handleSelectMenu = (e, id, bool=false) => {
    const val = e.target.checked;
    const arr = cloneDeep(selectData);
    if(val) {
      arr.push(id);
    } else {
      pull(arr,id);
    }
    setSelectData(arr);
    if(bool) {
      setTwoMenu(undefined);
    }
  }

  //点击一级菜单
  const handleClickOneMenu = id => {
    const renderData = getMenuData();
    const obj = find(renderData, [ 'id', id]);
    if(obj.hasChildren) {
      const val = obj.children[0].id;
      setOneMenu(id);
      setTwoMenu(val);
    } else {
      setOneMenu(id);
    }
  }

  //点击二级菜单
  const handleClickTwoMenu = id => {
    setTwoMenu(id);
  }

  const onCancel = () => {
    setOpen(false);

  }

  const afterClose = () => {
    if(isOk) {
      handleOk();
    } 
    handleCancel();
  }

  //点击切换不同的菜单
  const handleSwitchType = e => {
    const val = e.target.value;
    setOneMenu(undefined);
    setTwoMenu(undefined);
    setMenuType(val);
  }

  //根据当前tab渲染不同的数据
  const getMenuData = () => {
    if(menuType == 'web') {
      return data.menu || [];
    }
    return data.appMenu || [];
  }

  //点击app的一级菜单
  const handleSelectAppMenu = (e, id) => {
    const val = e.target.checked;
    const arr = cloneDeep(selectData);
    if(val) {
     if(id == 567 && arr.includes('342')) {
        return message.info('该功能与拿货互斥！')
     } else if(id == 342 && arr.includes('567')) {
        return message.info('该功能与送货上门-备货互斥！')
     } else {
        arr.push(id);
     }
    } else {
      pull(arr,id);
    }
    setOneMenu(id);
    setSelectData(arr);
  }

  //点击app的二级菜单
  const handleSelectTwoMenu = (e, id) => {
    const val = e.target.checked;
    const arr = cloneDeep(selectData);
    if(val) {
      arr.push(id);
    } else {
      pull(arr,id);
    }
    setSelectData(arr);
  }
  
  return (
    <CommonModal
      title={ id ? '编辑角色' : '新增角色' }
      open={open}
      onOk={onOk}
      onCancel={onCancel}
      width={850}
      afterClose={afterClose}
    >
        <Form
          {...layout1}
          form={form}
          name='role-manage-setrole'
          style={{ marginRight: '16px' }}
        >
          <Form.Item name="roleName" initialValue={roleName} label="角色名称" rules={[{ required: true, message: '请填写角色名称' }]}>
            <Input placeholder='请输入角色名称,最多30个字符' maxLength='30' disabled={roleType==3 ? true : false}/>
          </Form.Item>
          <Form.Item name="note" initialValue={note} label="备注" >
            <TextArea rows='2' maxLength='120' placeholder='请输入备注,最多120个字符' />
          </Form.Item>
        </Form>
        <div className='flex' style={{ margin: '0px 16px 16px 16px', alignItems: 'center' }}>
          <span style={{ margin: 0 }} className={ styles.fontTitle }>界面权限设置：</span>
          <Radio.Group value={menuType} onChange={handleSwitchType} buttonStyle="solid">
            <Radio.Button value="web">ERP系统</Radio.Button>
            <Radio.Button value="app">仓储APP</Radio.Button>
          </Radio.Group>
        </div>
        <div className="flex" style={{ margin: '0px 16px' }}>
          <div style={{ width: '290px', overflow: 'auto', borderRight: '4px solid #ccc' }}>
            <span className={ styles.fontTitle }>主菜单列表：</span>
            <div style={{ display: 'flex', flexWrap: 'wrap' }}>
              {
                getMenuData().map( v => {
                  if(menuType == 'app') {
                    return (
                      <Checkbox key={v.id}  className={ styles.normal } style={{ marginLeft: '0px', width: v.id == 567 ? '140px': '120px' }} onChange={(e) => handleSelectAppMenu(e, v.id)} checked={getChecked(v.id)}><span>{v.title}
                                              {/* {
                            v.id == 567 ? 
                          <Popover content={<div style={{width: '200px'}}>此权限与现有的备货权限互斥，若角色同事拥有这两个角色则对应的拿货权限将被覆盖失效</div>}><span style={{textIndent:'2px', cursor:'pointer', position: 'absolute'}}><IconFont type='iconwenhao1' /></span> </Popover>   
                            : ''
                        } */}
                      </span></Checkbox>
                    )
                  }
                  if(v.hasChildren) {
                    return (
                      <span key={v.id} className={v.id == oneMenu ? styles.select : styles.normal } onClick={() => handleClickOneMenu(v.id)}>{v.title}</span>
                    )
                  } else {
                    return (
                      // v.title == '首页' ?
                      // null
                      // :
                      <span onClick={() => handleClickOneMenu(v.id)} key={v.id} className={v.id == oneMenu ? styles.select : styles.normal } style={{ display: 'flex', alignItems: 'center' }}>
                        <Checkbox onChange={(e) => handleSelectMenu(e, v.id)} disabled={true} checked={getChecked(v.id)}/>
                        <span style={{ marginLeft: '8px' }}>{v.title}</span>
                      </span>
                    )
                  }
                })
              }
            </div>
          </div>
          <div style={{ flex: '1' }}>
            {renderOneMenu()}
            {renderTwoMenu()}
          </div>
        </div>
    </CommonModal>
  )
}